package com.example.mydownloader.netty.outBound

import com.example.mydownloader.mymodule.encrypt.AESCryptUtil
import com.example.mydownloader.mymodule.gson.GsonUtil
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.netty.NettyManager
import com.example.mydownloader.netty.NettyMsg
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelOutboundHandlerAdapter
import io.netty.channel.ChannelPromise

/**
 * @Description:
 * Netty消息加密处理
 * @author Wallace
 * @Date 2022/2/14 16:44
 */
class NettyMsgEncryptHandler : ChannelOutboundHandlerAdapter() {

    private var aesKey = NettyManager.aesKey

    override fun write(ctx: ChannelHandlerContext?, msg: Any, promise: ChannelPromise?) {
        val jsonString = (msg as? ByteBuf)?.toString(Charsets.UTF_8)
        LogUtil.i("jsonString = $jsonString")
        if (jsonString != null) {
            val cipher = AESCryptUtil.encryptAndEncode(
                jsonString.toByteArray(),
                aesKey!!.getSecretKeySpec(),
                aesKey!!.iv
            )
            if (cipher != null) {
                LogUtil.i(
                    "send message to server[${
                        ctx?.channel()?.remoteAddress()
                    }] : ${cipher.toString(Charsets.UTF_8)}"
                )
                ctx?.writeAndFlush(cipher)
            }
        } else {
            LogUtil.d("msg.javaClass = ${msg.javaClass}")
        }
    }
}